package com.it.controller;


import com.it.domain.BlogCommentEntity;
import com.it.domain.UserEntity;
import com.it.service.BlogService;
import com.it.service.BlogCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

/**
 * @author : code1997
 * @date : 2021/9/9 22:46
 */
@Controller
public class BlogCommentController {

    @Autowired
    private BlogCommentService commentService;

    @Autowired
    private BlogService blogService;

    @Value("${comment.avatar}")
    private String avatar;

    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model) {

        model.addAttribute("comments", commentService.listCommentByBlogId(blogId));
        return "blog::commentList";
    }

    @PostMapping("/comments")
    public String post(BlogCommentEntity blogCommentEntity, HttpSession session) {
        UserEntity userEntity = (UserEntity) session.getAttribute("user");
        Long blogId = blogCommentEntity.getBlog().getId();
        blogCommentEntity.setBlog(blogService.getBolg(blogId));
        if (userEntity != null) {
            //当前用户登陆了，是管理员，就从session中获取信息，并声明为管理员用户
            blogCommentEntity.setAvatar(userEntity.getAvatar());
            blogCommentEntity.setAdminComment(true);
        } else {
            blogCommentEntity.setAvatar(avatar);
        }
        commentService.saveComment(blogCommentEntity);
        return "redirect:/comments/" + blogCommentEntity.getBlog().getId();
    }
}
